import * as grpc from '@grpc/grpc-js';
import { CoreServiceService, IExecutionRequest, IExecutionResponse } from '../proto/core_service_grpc_pb';
import { ExecutionRequest, ExecutionResponse } from '../proto/core_service_pb';
import { Registry } from '../registry';

export class GrpcServer {
    private server: grpc.Server;
    private registry: Registry;

    constructor(registry: Registry) {
        this.registry = registry;
        this.server = new grpc.Server();
        this.setupServices();
    }

    private setupServices() {
        this.server.addService(CoreServiceService, {
            execute: this.execute.bind(this),
            loadAdapter: this.loadAdapter.bind(this)
        });
    }

    private execute(call: grpc.ServerUnaryCall<IExecutionRequest, IExecutionResponse>, callback: grpc.sendUnaryData<IExecutionResponse>) {
        try {
            const request = call.request as ExecutionRequest;
            // 协议转换和请求处理逻辑
            const response = new ExecutionResponse();
            response.setStatus(0);
            callback(null, response);
        } catch (err) {
            const response = new ExecutionResponse();
            response.setStatus(1);
            callback(err, response);
        }
    }

    private loadAdapter(call: grpc.ServerUnaryCall<IAdapterRequest, IAdapterResponse>, callback: grpc.sendUnaryData<IAdapterResponse>) {
        // 适配器加载逻辑
    }

    start(port: number) {
        this.server.bindAsync(
            `0.0.0.0:${port}`,
            grpc.ServerCredentials.createInsecure(),
            (err, port) => {
                if (err) {
                    console.error('gRPC server failed to start:', err);
                    return;
                }
                console.log(`gRPC server running on port ${port}`);
                this.server.start();
            }
        );
    }
}